const WebSocket = require('ws');
// 创建 WebSocket 服务器
const server = new WebSocket.Server({ port: 8080 });
const clients = new Set();

server.on('connection', (ws) => {
    clients.add(ws);
    console.log('A new client connected');

    ws.on('message', (message) => {
        let receivedMessage;
        console.log(`Received: ${message}`);
        if (Buffer.isBuffer(message)) {
            receivedMessage = message.toString();  // 将 Buffer 转换为字符串
        } else {
            receivedMessage = message; // 如果是字符串，直接使用
        }
        // 将接收到的消息广播给所有连接的客户端
        clients.forEach(client => {
            if (client !== ws && client.readyState === WebSocket.OPEN) {
                client.send(receivedMessage);
            }
        });
    });

    ws.on('close', () => {
        clients.delete(ws);
        console.log('A client disconnected');
    });
});

console.log('WebSocket server is running on ws://localhost:8080');